from django.db import connection

from app import settings
from app.decorator import jwt_auth
from app.service import member, shop
from app.service.member import get_member_by_username, query_members_by_keyword, get_member_by_id
from libs.auth import make_member_password
from libs.common import success, error
from libs.db import DB
from libs.form import RawJsonForm
from libs.time_helper import ts_to_time_str
from libs.type_is import is_telephone


@jwt_auth
def create(request, auth):
    form = RawJsonForm(request.body)
    username = form.get('username')
    password = form.get('password', '')
    if not is_telephone(username):
        return error('无效的手机号')
    db_mem = get_member_by_username(username, ['id'])
    if db_mem.get('id', 0) > 0:
        return error('手机号已存在')
    shop_id = auth.get('shop_id')
    if password == '':
        return error('密码不能为空')
    else:
        raw_pass = password
    member_data = {
        'username': username,
        'usdt_value': 0,
        'user_level': 0,
        'is_del': 0,
        'usdt_freezing': 0,
        'point': 0,
        'coupon': 0,
        'coupon_freezing': 0,
        'point_freezing': 0,
        'password': make_member_password(raw_pass),
        'reference_name': username,
        'is_shop': 0,
        'shop_level': 0,
        'register_time': ts_to_time_str(time_format="%Y-%m-%d %H:%M:%S"),
        'icon': settings.MEMBER_DEFAULT_ICON
    }
    new_member_info = {}
    building_no = form.get('building_no', None)
    if building_no is not None:
        new_member_info.update({'building_no': building_no})
    unit = form.get('unit', None)
    if unit is not None:
        new_member_info.update({'unit': unit})
    level = form.get('level', None)
    if level is not None:
        new_member_info.update({'level': level})
    house_number = form.get('house_number', None)
    if house_number is not None:
        new_member_info.update({'house_number': house_number})
    name = form.get('name', None)
    if name is not None:
        new_member_info.update({'name': name})
    member_id, err = member.add_member_v2(shop_id, member_data, new_member_info)
    if err is not None:
        return error(err)
    return success({'id': member_id})


@jwt_auth
def detail(request, auth):
    try:
        form = RawJsonForm(request.body)
        member_id = form.get_int('member_id')
        db_mem_info = {}
        if member_id <= 0:
            username = form.get('username')
            if username == '':
                return error('无效的会员号/手机号')
            row = get_member_by_username(username)
        else:
            row = get_member_by_id(member_id)
        if row.get('id') <= 0:
            return error('会员信息不存在')
        db = DB('table_member_info')
        fields = ['phone', 'building_no', 'unit', 'level', 'level', 'house_number', 'name', 'created_at', 'com_name', 'shop_name']
        db_username = row.get('username', '')
        if db_username != '':
            db_mem_info = db.one(fields, {'username': db_username})
        row.update({'member_info': db_mem_info})
    except Exception as e:
        print(e)
        return error('获取会员信息异常')
    return success(row)


@jwt_auth
def query(request, auth):
    form = RawJsonForm(request.body)
    keyword = form.get('keyword')
    page = form.get_page()
    if keyword == '':
        return error('无效的会员号/手机号')
    rows = query_members_by_keyword(keyword, page)
    return success(rows)


@jwt_auth
def update(request, auth):
    form = RawJsonForm(request.body)
    member_id = form.get_int('id', 0)
    if member_id <= 0:
        return error('无效的会员ID')
    with connection.cursor() as cursor:
        db_mem = get_member_by_id(member_id, cursor, ['id', 'username'])
        if db_mem.get('id', 0) == 0:
            return error('会员信息不存在')
        new_member_info = {}
        building_no = form.get('building_no', None)
        if building_no is not None:
            new_member_info.update({'building_no': building_no})
        unit = form.get('unit', None)
        if unit is not None:
            new_member_info.update({'unit': unit})
        level = form.get('level', None)
        if level is not None:
            new_member_info.update({'level': level})
        house_number = form.get('house_number', None)
        if house_number is not None:
            new_member_info.update({'house_number': house_number})
        name = form.get('name', None)
        if name is not None:
            new_member_info.update({'name': name})
        if len(new_member_info.keys()) > 0:
            username = db_mem.get('username')
            db = DB('table_member_info', conn=cursor)
            db_member_info = db.one(['id'], {'username': username})
            db_member_info_id = db_member_info.get('id', 0)
            if db_member_info_id == 0:
                shop_id = auth.get('shop_id')
                db_shop = shop.get_shop(shop_id, ['id', 'shop_name'])
                db_shop_name = db_shop.get('shop_name', '')
                member_info = {
                    'username': username,
                    'phone': '',
                    'building_no': '1',
                    'unit': '1',
                    'level': '1',
                    'house_number': '1',
                    'name': '',
                    'com_id': 0,
                    'com_name': '其它',
                    'shop_id': shop_id,
                    'shop_name': db_shop_name,
                }
                member_info.update(new_member_info)
                _, err = db.insert(member_info)
            else:
                _, err = db.update(new_member_info, {'id': db_member_info_id})
            if err is not None:
                return error(err)
    return success()
